import type { ActionType, ProColumns, ProFormInstance } from '@ant-design/pro-components';
import {
    FooterToolbar,
    PageContainer,
    ProFormText,
    ProTable,
    ProForm,
} from '@ant-design/pro-components';
import { Button, Drawer, message, Switch } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { queryProductPurchaseList, updateProductPurchaseStatus, syncProductStatus,updateProductEdit} from '@/services/ant-design-pro/mjProductPurchase';

const TableList: React.FC = () => {
    const [uploadUrl, setUploadUrl] = useState<string>('');
    const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
    const [isEditing, setIsEditing] = useState<boolean>(false);
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<TableListItem>();
    const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
    const formRef = useRef<ProFormInstance>();
    const [activeKey, setActiveKey] = useState<string>('服务时长');
    const [columns, setColumns] = useState<ProColumns[]>([]);

    const handleRemove = async (selectedRows: TableListItem[]) => {
        const hide = message.loading('正在删除');
        if (!selectedRows) return true;

        try {
            await removeAttribute({
                id: selectedRows.map((row) => row.id),
            });
            hide();
            message.success('删除成功，即将刷新');
            return true;
        } catch (error) {
            hide();
            message.error('删除失败，请重试');
            return false;
        }
    };

    const confirm = async (id: number) => {
        await removeAttribute({ id });
        message.success('删除成功');
        actionRef.current?.reloadAndRest?.();
    };

    const CustomSwitch = ({ value, onChange }) => {
        const handleChange = (checked) => {
            onChange(checked ? 'true' : 'false');
        };
        return (
            <Switch
                checked={value === 'true'}
                onChange={handleChange}
            />
        );
    };

    const handleAdd = async (fields: TableListItem) => {
        const hide = message.loading('正在添加');
        try {
            await addAttribute({ ...fields, attributeImgurl: uploadUrl, title: activeKey });
            hide();
            message.success('添加成功');
            return true;
        } catch (error) {
            hide();
            message.error('添加失败，请重试！');
            return false;
        }
    };

    const handleUpdate = async (currentRow?: TableListItem) => {
        const hide = message.loading('正在配置');
        try {
            await updateProductPurchaseStatus({
                ...currentRow,
            });
            hide();
            message.success('配置成功');
            actionRef.current?.reloadAndRest?.();
            return true;
        } catch (error) {
            hide();
            message.error('配置失败，请重试！');
            return false;
        }
    };

    const handleUpdateStatus = async (currentRow?: TableListItem) => {
        const hide = message.loading('正在配置');
        try {
            await updateProductEdit({
                ...currentRow,
            });
            hide();
            message.success('配置成功');
            actionRef.current?.reloadAndRest?.();
            return true;
        } catch (error) {
            hide();
            message.error('配置失败，请重试！');
            return false;
        }
    };


    useEffect(() => {
        if (drawerVisible && formRef.current) {
            formRef.current.setFieldsValue(currentRow || {});
        }
    }, [drawerVisible, currentRow]);

    useEffect(() => {
        const fetchColumns = async () => {
            try {
                const response = await queryProductPurchaseList({});
                setColumns([
                    ...response.purchasePriceVoList,
                    {
                        title: '操作',
                        fixed: 'right',
                        width: 80,
                        dataIndex: 'option',
                        valueType: 'option',
                        render: (_, record) => [
                            <a
                                key="config"
                                onClick={() => {
                                    setCurrentRow(record);
                                    setIsEditing(true);
                                    setDrawerVisible(true);
                                }}
                            >
                                编辑
                            </a>
                        ],
                    },
                    {
                        title: '启用状态',
                        dataIndex: 'status',
                        fixed: 'right',
                        valueType: 'switch',
                        width: 100,
                        render: (_, record) => (
                            <Switch
                            checked={record.status === '0'}
                                onChange={(checked) => handleUpdateStatus({ id:record.id, status: checked ? '0' : '1' })}
                            />
                        ),
                    }
                ]);
            } catch (error) {
                console.error('Failed to fetch columns config:', error);
            }
        };

        fetchColumns();
    }, []);

    return (
        <PageContainer header={{ title: '' }}>
            <ProTable<TableListItem>
                actionRef={actionRef}
                rowKey="id"
                search={false}
                scroll={{ x: 2500 }}
                request={(params) => queryProductPurchaseList({ ...params })}
                columns={columns.filter((colum) => colum.type !== 'switch')}
                toolBarRender={() => [
                    <Button
                      key="button"
                      type="primary"
                      onClick={ async () => {
                        await syncProductStatus({})
                        message.success('数据同步成功');
                        actionRef.current?.reloadAndRest?.();
                      }}
                    >
                      获取最新数据
                    </Button>,
                  ]}
            />
            {selectedRowsState?.length > 0 && (
                <FooterToolbar
                    extra={
                        <div>
                            已选择{' '}
                            <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项 &nbsp;&nbsp;
                        </div>
                    }
                >
                    <Button
                        onClick={async () => {
                            await handleRemove(selectedRowsState);
                            setSelectedRows([]);
                            actionRef.current?.reloadAndRest?.();
                        }}
                    >
                        批量删除
                    </Button>
                </FooterToolbar>
            )}
            <Drawer
                title={isEditing ? "编辑属性" : "新建属性"}
                width={600}
                onClose={() => setDrawerVisible(false)}
                open={drawerVisible}
                destroyOnClose
            >
                <ProForm
                    layout="vertical"
                    formRef={formRef}
                    labelCol={{span: 6, offset: 12}}
                    initialValues={currentRow || {}}
                    onFinish={async (value) => {
                        let success = false;
                        if (isEditing) {
                            success = await handleUpdate({ ...currentRow, ...value });
                        } else {
                            success = await handleAdd(value);
                        }

                        if (success) {
                            setDrawerVisible(false);
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    }}
                >
                    {columns.map((column) => (
                        column.dataIndex !== 'option' && column.type && (
                            column.type === 'switch' ? (
                                <ProForm.Item key={column.dataIndex} name={column.dataIndex} label={column.title}>
                                    <CustomSwitch />
                                </ProForm.Item>
                            ) : (
                                <ProFormText key={column.dataIndex} name={column.dataIndex} label={column.title} />
                            )
                        )
                    ))}

                </ProForm>
            </Drawer>
        </PageContainer>
    );
};

export default TableList;